package com.shaoshaohuo.app.ui.ec;

import java.util.ArrayList;
import java.util.List;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.BusinessSeller;
import com.shaoshaohuo.app.entity.BusinessSellerEntity;
import com.shaoshaohuo.app.entity.Buyer;
import com.shaoshaohuo.app.entity.BuyerEntity;
import com.shaoshaohuo.app.entity.PurchaseHall;
import com.shaoshaohuo.app.entity.PurchaseHallEntity;
import com.shaoshaohuo.app.entity.SupplyRecord;
import com.shaoshaohuo.app.entity.SupplyRecordEntity;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.adapter.DumpGoodsAdapter;
import com.shaoshaohuo.app.adapter.MerchantsDetailListAdapter;
import com.shaoshaohuo.app.adapter.PurchaseListAdapter;
import com.shaoshaohuo.app.adapter.SellerListAdapter;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;
import com.shaoshaohuo.app.view.XListView.IXListViewListener;
import com.shaoshaohuo.app.utils.DeviceHelper;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author: yusonglin
 * @类 说 明:
 * @version 1.0
 * @创建时间：2015年9月1日 上午10:54:31
 * 
 */
public class SearchActivity extends BaseActivity implements OnClickListener, IXListViewListener {

	// 1 找买家 ，2 找采购 3 找供应 4 找卖家
	private static final int TYPEID_FIND_BUYER = 1;
	private static final int TYPEID_FIND_SELLER = 4;
	private static final int TYPEID_SUPPLY = 3;
	private static final int TYPEID_PURCHASE = 2;

	private TopbarView mTopbarView;

	private View mSearchLayout;
	private ImageView mSearchImage;
	private EditText mSearchEdit;
	private Handler mHandler = new Handler();

	private XListView mListView;

	private TextView mFindBuyerText;
	private TextView mFindSellerText;
	private TextView mSupplyText;
	private TextView mPurchaseText;

	// size, cursor, action, typeid
	private List<Buyer> mBuyerList = new ArrayList<Buyer>();
	private List<BusinessSeller> mSellerList = new ArrayList<BusinessSeller>();
	private List<SupplyRecord> mSupplyList = new ArrayList<SupplyRecord>();
	private List<PurchaseHall> mPurchaseList = new ArrayList<PurchaseHall>();
	private int size = 10;
	private String cursor = "";
	private String action = ListViewAction.NEW;
	private int typeid = TYPEID_FIND_BUYER;

	private MerchantsDetailListAdapter<Buyer> mBuyerAdapter;
	private SellerListAdapter<BusinessSeller> mSellerAdapter;
	private DumpGoodsAdapter<SupplyRecord> mBupplyAdapter;
	private PurchaseListAdapter<PurchaseHall> mPurchaseAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		initView();
		setUpView();
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mListView = (XListView) this.findViewById(R.id.listview_data_list);
		
		mSearchLayout = this.findViewById(R.id.layout_search);
		mSearchImage = (ImageView) findViewById(R.id.imageview_search);
		mSearchEdit = (EditText) findViewById(R.id.edittext_search);

		mFindBuyerText = (TextView) this.findViewById(R.id.textview_find_buyer);
		mFindSellerText = (TextView) this.findViewById(R.id.textview_find_seller);
		mSupplyText = (TextView) this.findViewById(R.id.textview_supply);
		mPurchaseText = (TextView) this.findViewById(R.id.textview_purchase);
	}

	private void setUpView() {
		mTopbarView.setCenterText("搜索");
		mTopbarView.setLeftView(true, true);

		mSearchEdit.requestFocus();

		mFindBuyerText.setOnClickListener(this);
		mFindSellerText.setOnClickListener(this);
		mSupplyText.setOnClickListener(this);
		mPurchaseText.setOnClickListener(this);
		setListView();
		onClick(mFindBuyerText);
		
		mSearchEdit.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP){
					
					search();
					
					return true;
				}
				return false;
			}

		});
	}

	private void search() {
		DeviceHelper.hideIME(mSearchEdit);
		String keywords = mSearchEdit.getText().toString().trim();
		if(TextUtils.isEmpty(keywords)){
			Toast.makeText(SearchActivity.this, "请输入要搜索的内容", 0).show();
			return;
		}
//		search(true);
		switch (typeid) {
		case TYPEID_FIND_BUYER:
			mFindBuyerText.setSelected(false);
			onClick(mFindBuyerText);
			break;
		case TYPEID_FIND_SELLER:
			mFindSellerText.setSelected(false);
			onClick(mFindSellerText);
			break;
		case TYPEID_SUPPLY:
			mSupplyText.setSelected(false);
			onClick(mSupplyText);
			break;
		case TYPEID_PURCHASE:
			mPurchaseText.setSelected(false);
			onClick(mPurchaseText);
			break;
		}
		
	}
	
	private boolean flag = true;

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus && flag) {
			flag = false;
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					DeviceHelper.showIME(mSearchEdit);
				}
			}, 200);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.textview_find_buyer:
			if (mFindBuyerText.isSelected()) {
				return;
			}
			mFindBuyerText.setSelected(true);
			mFindSellerText.setSelected(false);
			mSupplyText.setSelected(false);
			mPurchaseText.setSelected(false);

			mBuyerList.clear();
			typeid = TYPEID_FIND_BUYER;
			if(mBuyerAdapter!=null){
				mListView.setAdapter(mBuyerAdapter);
			}
			break;
		case R.id.textview_find_seller:
			if (mFindSellerText.isSelected()) {
				return;
			}
			mFindBuyerText.setSelected(false);
			mFindSellerText.setSelected(true);
			mSupplyText.setSelected(false);
			mPurchaseText.setSelected(false);
			mSellerList.clear();
			typeid = TYPEID_FIND_SELLER;
			if(mSellerAdapter!=null){
				mListView.setAdapter(mSellerAdapter);
			}
			break;
		case R.id.textview_supply:
			if (mSupplyText.isSelected()) {
				return;
			}
			mFindBuyerText.setSelected(false);
			mFindSellerText.setSelected(false);
			mSupplyText.setSelected(true);
			mPurchaseText.setSelected(false);
			
			mSupplyList.clear();
			typeid = TYPEID_SUPPLY;
			if(mBupplyAdapter!=null){
				mListView.setAdapter(mBupplyAdapter);
			}
			break;
		case R.id.textview_purchase:
			if (mPurchaseText.isSelected()) {
				return;
			}
			mFindBuyerText.setSelected(false);
			mFindSellerText.setSelected(false);
			mSupplyText.setSelected(false);
			mPurchaseText.setSelected(true);

			mPurchaseList.clear();
			typeid = TYPEID_PURCHASE;
			if(mPurchaseAdapter!=null){
				mListView.setAdapter(mPurchaseAdapter);
			}
			break;
		}
		
		cursor = "";
		action = ListViewAction.NEW;
		search(true);
	}

	private void search(boolean isLoading) {
		String keyword = mSearchEdit.getText().toString().trim();
		if(TextUtils.isEmpty(keyword)){
			return;
		}
		if(isLoading){
			startLoadingDialog();
		}
		Class<? extends BaseEntity> clazz = null;
		switch (typeid) {
		case TYPEID_FIND_BUYER:
			clazz = BuyerEntity.class;
			break;
		case TYPEID_FIND_SELLER:
			clazz = BusinessSellerEntity.class;
			break;
		case TYPEID_SUPPLY:
			clazz = SupplyRecordEntity.class;
			break;
		case TYPEID_PURCHASE:
			clazz = PurchaseHallEntity.class;
			break;
		}
		RequestService.getInstance().searchEc(this, keyword, size + "", cursor, action, typeid + "", clazz,
				new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						dismissLoadingDialog();
						if (resultData.isOk()) {
							setAdapter(resultData);
						} else {
							showToast(resultData.getMsg());
						}
						onLoad();
					}

					@Override
					public void onFailed(int requestCode, Exception error, String msg) {
						dismissLoadingDialog();
						showToast(R.string.please_check_network);
						onLoad();
					}
				});
	}

	protected void setAdapter(BaseEntity resultData) {
		switch (typeid) {
		case TYPEID_FIND_BUYER:
			setBuyersAdapter(resultData);
			break;
		case TYPEID_FIND_SELLER:
			setSellerAdapter(resultData);
			break;
		case TYPEID_SUPPLY:
			setSupplyAdapter(resultData);
			break;
		case TYPEID_PURCHASE:
			setPurchaseAdapter(resultData);
			break;
		}
	}
	
	protected void setPurchaseAdapter(BaseEntity resultData) {
		PurchaseHallEntity entity = (PurchaseHallEntity) resultData;
		List<PurchaseHall> list = entity.getData().getList();
		mPurchaseList.addAll(list);
		if ((mPurchaseList.size() < size) || (action.equals(ListViewAction.HISTORY) && list.size() < size)) {
			// mListView.setPullLoadEnable(false);
			mListView.endLoadingMore("没有更多了");
		}
		if (mPurchaseAdapter == null) {
			mPurchaseAdapter = new PurchaseListAdapter<PurchaseHall>(this, mPurchaseList, false);
			mListView.setAdapter(mPurchaseAdapter);
		} else {
			mPurchaseAdapter.setData(mPurchaseList);
//			mAdapter.notifyDataSetChanged();
		}
	}
	
	protected void setSupplyAdapter(BaseEntity resultData) {
		SupplyRecordEntity entity = (SupplyRecordEntity) resultData;
		List<SupplyRecord> list = entity.getData().getList();
		mSupplyList.addAll(list);
		if ((mSupplyList.size() < size) || (action.equals(ListViewAction.HISTORY) && list.size() < size)) {
			// mListView.setPullLoadEnable(false);
			mListView.endLoadingMore("没有更多了");
		}
		if (mBupplyAdapter == null) {
			mBupplyAdapter = new DumpGoodsAdapter<SupplyRecord>(this, mSupplyList, false);
			mListView.setAdapter(mBupplyAdapter);
		} else {
			mBupplyAdapter.setData(mSupplyList);
		}
	}

	protected void setSellerAdapter(BaseEntity resultData) {

		BusinessSellerEntity entity = (BusinessSellerEntity) resultData;
		List<BusinessSeller> list = entity.getData().getList();
		mSellerList.addAll(list);
		if ((mSellerList.size() < size) || (action.equals(ListViewAction.HISTORY) && list.size() < size)) {
			// mListView.setPullLoadEnable(false);
			mListView.endLoadingMore("没有更多了");
		}
		if (mSellerAdapter == null) {
			mSellerAdapter = new SellerListAdapter<BusinessSeller>(this, mSellerList, false);
			mListView.setAdapter(mSellerAdapter);
		} else {
			mSellerAdapter.setData(mSellerList);
		}
	}

	protected void setBuyersAdapter(BaseEntity resultData) {
		BuyerEntity entity = (BuyerEntity) resultData;
		List<Buyer> list = entity.getData().getList();
		mBuyerList.addAll(list);
		if ((mBuyerList.size() < size) || (action.equals(ListViewAction.HISTORY) && list.size() < size)) {
			// mListView.setPullLoadEnable(false);
			mListView.endLoadingMore("没有更多了");
		}
		if (mBuyerAdapter == null) {
			mBuyerAdapter = new MerchantsDetailListAdapter<Buyer>(this, mBuyerList, false);
			mListView.setAdapter(mBuyerAdapter);
		} else {
			mBuyerAdapter.setData(mBuyerList);
		}
	}


	private void setListView() {
		mListView.setPullLoadEnable(true);
		mListView.setPullRefreshEnable(true);
		mListView.setXListViewListener(this);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				switch (typeid) {
				case TYPEID_FIND_BUYER:
//					Buyer buyer = (Buyer) parent.getItemAtPosition(position);
//                    Intent buyerintent = new Intent(SearchActivity.this, MarketDetailActivity.class);
//                    buyerintent.putExtra(ExtraName.id, buyer.getMarketid());
//                    startActivity(buyerintent);
					break;
				case TYPEID_FIND_SELLER:
					BusinessSeller seller = (BusinessSeller) parent.getItemAtPosition(position);
                    Intent sellerintent = new Intent(SearchActivity.this, SupplierDetailActivity.class);
                    sellerintent.putExtra(ExtraName.id, seller.getId());
                    startActivity(sellerintent);
					break;
				case TYPEID_SUPPLY:
					SupplyRecord supply = (SupplyRecord) parent.getItemAtPosition(position);
					Intent intent = new Intent(SearchActivity.this, SupplyDetailActivity.class);
					intent.putExtra(ExtraName.id, supply.getId());
					startActivity(intent);
					break;
				case TYPEID_PURCHASE:
					PurchaseHall purchase = (PurchaseHall) parent.getItemAtPosition(position);
					Intent purchaseintent = new Intent(SearchActivity.this, PurchaseDetailActivity.class);
					purchaseintent.putExtra(ExtraName.id, purchase.getId());
					startActivity(purchaseintent);
					break;
				}
			}
		});
	}

	@Override
	public void onRefresh() {
		switch (typeid) {
		case TYPEID_FIND_BUYER:
			if (mBuyerList.size() > 0) {
				cursor = mBuyerList.get(0).getCursor();
			} else {
				cursor = "";
			}
			break;
		case TYPEID_FIND_SELLER:
			if (mSellerList.size() > 0) {
				cursor = mSellerList.get(0).getCursor();
			} else {
				cursor = "";
			}
			break;
		case TYPEID_SUPPLY:
			if (mSupplyList.size() > 0) {
				cursor = mSupplyList.get(0).getCursor();
			} else {
				cursor = "";
			}
			break;
		case TYPEID_PURCHASE:
			if (mPurchaseList.size() > 0) {
				cursor = mPurchaseList.get(0).getCursor();
			} else {
				cursor = "";
			}
			break;
		}
		action = ListViewAction.NEW;
		mListView.setPullLoadEnable(true);
		search(false);
	}
	

	@Override
	public void onLoadMore() {
		
		switch (typeid) {
		case TYPEID_FIND_BUYER:
			if (mBuyerList.size() > 0) {
				cursor = mBuyerList.get(mBuyerList.size() - 1).getCursor();
			} else {
				cursor = "";
			}
			break;
		case TYPEID_FIND_SELLER:
			if (mSellerList.size() > 0) {
				cursor = mSellerList.get(mSellerList.size() - 1).getCursor();
			} else {
				cursor = "";
			}
			break;
		case TYPEID_SUPPLY:
			if (mSupplyList.size() > 0) {
				cursor = mSupplyList.get(mSupplyList.size() - 1).getCursor();
			} else {
				cursor = "";
			}
			break;
		case TYPEID_PURCHASE:
			if (mPurchaseList.size() > 0) {
				cursor = mPurchaseList.get(mPurchaseList.size() - 1).getCursor();
			} else {
				cursor = "";
			}
			break;
		}
		action = ListViewAction.HISTORY;
		search(false);
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
	}
	
	@Override
	protected void onDestroy() {
		DeviceHelper.hideIME(mTopbarView);
		super.onDestroy();
	}

}
